04. The Gotchas of Operators

The Gotchas of Operators Part 1

The Gotchas of Operators Part 2

Types of Expressions

There are four types of expressions found in Swift. Remember that expressions are statements that return or evaluate to a single value.

Primary Expressions

Primary expressions are the most simple kind of expression found in Swift. A primary expression is an expression that can stand alone and return a value:

Here, "poundsOfFlour" evaluates to 2.

Here, "poundsOfFlour" evaluates to 2.

Prefix Expressions

Prefix Expressions

Prefix expressions combine an optional prefix operator with an expression—typically a primary expression (variable):

var counter = 3
var negativeCounter = -counter

Here, -counter is a prefix expression combining the a negative sign (called unary minus operator in Swift) with the counter variable.

Binary Expressions

Binary expressions combine an infix binary operator with a left-hand expression and a right-hand expression. Binary expressions have the following form: leftHandSide operator rightHandSide.

This binary expression evaluates to 2 because 7 divided by 5 has a remainder of 2.

This binary expression evaluates to 2 because 7 divided by 5 has a remainder of 2.

Postfix Expressions

Postfix Expressions

Postfix expressions are formed by applying a postfix operator to an expression. Syntactically, every primary expression is also a postfix expression.

The following expression uses the ! operator which we haven't seen before. Don't worry, we will explain this operator later when we talk about Optionals. We are just mentioning it here for completeness.

var optionalNumber: Int? = 3
optionalNumber!

If you would like to read about expressions in more detail, check out Apple’s documentation on Swift expressions.